package com.vm.db;

import com.vm.commons.CurrentUser;
import com.vm.model.LocalUserInfo;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月12日 下午7:39:23]
 * @Version: [v1.0]
 * 
 */
public class LocalUserInfoDao {

	private static final String TAG = "LocalUserInfoDao";


	public LocalUserInfoDao(Context context) {
		if (DBOpenHelper.db == null) {
			new DBOpenHelper(context);
		}
	}

	public synchronized void insert(LocalUserInfo localUserInfo) {
		Log.d(TAG, "insert");
		try {
			DBOpenHelper.db.execSQL(
					"INSERT INTO localUserInfo(userId,username,intergral,imageUrl) VALUES(?, ?,?,?)",
					new Object[] { localUserInfo.getUserId(),
							localUserInfo.getUsername(),
							localUserInfo.getIntergral(),
							localUserInfo.getImageUrl() });
		} catch (SQLException e) {
			Log.d(TAG, "insert---" + e.getMessage());
		}
	}

	public synchronized void delete() {
		Log.d(TAG, "delete");
		try {
			DBOpenHelper.db.execSQL("DELETE FROM localUserInfo");
		} catch (SQLException e) {
			Log.d(TAG, "delete---" + e.getMessage());
		}
	}

	public synchronized void update() {
		Log.d(TAG, "update");

		try {
			DBOpenHelper.db.execSQL("UPDATE localUserInfo SET intergral='"
					+ CurrentUser.INTERGRAL + "' WHERE userId='"
					+ CurrentUser.USERID + "'");
		} catch (SQLException e) {
			Log.d(TAG, "update---" + e.getMessage());
		}
	}

	public synchronized void updateLogo() {
		Log.d(TAG, "updateLogo");

		try {
			DBOpenHelper.db.execSQL("UPDATE localUserInfo SET imageUrl='"
					+ CurrentUser.IMAGEURL + "' WHERE userId='"
					+ CurrentUser.USERID + "'");
		} catch (SQLException e) {
			Log.d(TAG, "updateLogo---" + e.getMessage());
		}
	}

	public synchronized LocalUserInfo query() {
		Log.d(TAG, "query");
		Cursor c = null;
		LocalUserInfo localUserInfo = null;
		try {
			c = DBOpenHelper.db.rawQuery(
					"SELECT userId,username,intergral,imageUrl FROM localUserInfo",
					new String[] {});
			localUserInfo = null;
			if (c.moveToNext()) {
				localUserInfo = new LocalUserInfo();
				localUserInfo.setUserId(c.getString(0));
				localUserInfo.setUsername(c.getString(1));
				localUserInfo.setIntergral(c.getInt(2));
				localUserInfo.setImageUrl(c.getString(3));
			}
		} catch (Exception e) {
			Log.d(TAG, "query---" + e.getMessage());
		} finally {
			if(c!=null){
				c.close();
			}
		}
		return localUserInfo;
	}

}
